import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import compression from 'vite-plugin-compression'

export default defineConfig({
  plugins: [
    vue(),
    compression({
      algorithm: 'gzip',
      ext: '.gz'
    })
  ],
  server: {
    port: 3000,
    open: true,
    host: true,
    cors: true,
    // 热更新优化
    hmr: {
      overlay: true
    },
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  },
  // 预览服务器配置
  preview: {
    port: 4173,
    open: true,
    host: true
  },
  build: {
    target: 'es2015',
    minify: 'esbuild', // 使用更快的 esbuild 压缩
    sourcemap: process.env.MODE !== 'production',
    // 代码分割优化
    rollupOptions: {
      output: {
        manualChunks: (id) => {
          if (id.includes('node_modules')) {
            if (id.includes('vue')) return 'vendor-vue'
            if (id.includes('element-plus')) return 'vendor-element-plus'
            return 'vendor-other'
          }
        },
        // 文件名哈希优化
        chunkFileNames: 'assets/js/[name]-[hash].js',
        entryFileNames: 'assets/js/[name]-[hash].js',
        assetFileNames: 'assets/[ext]/[name]-[hash].[ext]'
      }
    },
    // 构建输出优化
    assetsInlineLimit: 4096, // 4KB 以下资源内联
    cssCodeSplit: true, // CSS 代码分割
    reportCompressedSize: false, // 禁用压缩大小报告（提升构建速度）
  },
  // 依赖预构建优化
  optimizeDeps: {
    include: ['vue', 'element-plus', '@monorepo-demo/components'],
    exclude: [],
    esbuildOptions: {
      target: 'es2015',
      define: {
        __VUE_OPTIONS_API__: 'true',
        __VUE_PROD_DEVTOOLS__: 'false'
      }
    }
  },

  resolve: {
    alias: {
      '@': '/src',
      '@components': '/src/components'
    }
  }
})
